﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using devtm.Configuration.Models;
using System.Collections;
using devtm.Helpers.Factories;

namespace devtm.Editor.Configuration.Data
{
    public class TemplateListeSelector: ConfigProperty
    {

        public TemplateListeSelector() { }

        public TemplateListeSelector(PropertyInfo propertyinfo, ElementSection instance, ListeSelectorAttribute attribut)
            : base(propertyinfo, instance)
        {

            PropertyInfo prop = instance.ConfigurationElement.GetType().GetProperty(attribut.PropertyName);

            if (prop == null)
                throw new FieldAccessException(attribut.PropertyName);

            List<Facad> l = new List<Facad>();
            IEnumerable i = (IEnumerable)prop.GetValue(instance.ConfigurationElement, null);
            foreach (var j in i)
                l.Add(new Facad(j, attribut.ShowLabel));
            this.Tag = l;
       

            //List<string> l = new List<string>();
            //IEnumerable i = (IEnumerable)prop.GetValue(instance.ConfigurationElement, null);

            //foreach (var j in i)
            //    l.Add(new Facad(j, attribut.ShowLabel));

            //this.Tag = l;


        }

        /// <summary>
        /// Runs the editor.
        /// </summary>
        public override void RunEditor() { }

        public override void Selector() { }

        public override object Value
        {
            get
            {

                var mabase = base.Value;

                if (this.Tag != null)
                    foreach (var item in this.Tag as IEnumerable)
                    {

                        var pp = item as Facad;

                        if (pp.Property1.Equals(mabase))
                            return item;
                    }
                return mabase;
            }
            set
            {

                var pp = value as Facad;
                if (pp != null)
                    base.Value = pp.Property1;
                else
                    base.Value = value;

            }
        }

    }
}
